#include "common.h"

int sockfd ;
struct sockaddr_in addr;
short PORT = 1234;
char *IP = "127.0.0.1";

void init()
{
	printf("尝试连接服务器...\n");
	if((sockfd = socket(PF_INET , SOCK_STREAM , 0)) == -1)
		perror("socket创建失败") , exit(-1);
	memset(&addr , 0 , sizeof(addr));
	addr.sin_family = PF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = inet_addr(IP);

		
}

void* thread_recv(void *p)
{
	char buf[BUFSIZE] = {};
	while(1)
	{
		memset(buf , 0x00 , sizeof(buf));
		if(recv(sockfd , buf , sizeof(buf) , 0) > 0)
		{
			printf("%s\n",buf);

		}
		else
			return ;
	}
}

void* thread_send(void *p)
{
	char buf[BUFSIZE] = {};	
	while(1)
	{
		memset(buf , 0 , sizeof(buf));
		//printf("请输入:");
		scanf("%s",buf);
		send(sockfd , buf , strlen(buf) , 0);
	}
}

void comm()
{
	//1、输入用户名
	char name[20] = {};
	printf("请输入用户名: ");
	scanf("%s",name);
	send(sockfd , name , sizeof(name) , 0);

	//2、启动线程接受消息
	pthread_t id1,id2 ;
	pthread_create(&id1 , 0 , thread_recv , 0);
	pthread_create(&id2 , 0 , thread_send , 0);

	//3、启动线程发送消息
	
/*
	char mess[BUFSIZE] = {};
	while(1)
	{
		memset(mess , 0x00 , sizeof(mess));
		scanf("%s",mess);
		send(sockfd , mess , strlen(mess) , 0);
	}*/
	
	pthread_join(id1 , 0);
	pthread_join(id2 , 0);

}

void quit()
{
	close(sockfd);
	printf("关闭应用...\n");
	exit(0);
}

int main()
{
	signal(SIGINT,quit);	
	init();
	comm();
	quit();
}
